package edu.usc.libtalk;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import edu.usc.libtalk.task.GetJSONArrayTask;
import edu.usc.libtalk.task.GetJSONObjectTask;
import edu.usc.libtalk.utils.ApplicationService;
import edu.usc.libtalk.utils.InternalConstant;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.PaintDrawable;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ZoomControls;

public class SSL2Activity extends Activity implements InternalConstant {
	private int mode; // 0: Chat mode, 1: Sign in mode
	private String library;
	private int user_level;
	private int user_seat;
	private String username;
	Intent intent;
	private static final String TAG = "SSL2Activity";	
	
	private Button seat1_bn;
	private Button seat2_bn;
	private Button seat3_bn;
	private Button seat4_bn;
	private ArrayList seatStatus;
	
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ssl2);
        
        final WebView mWebView = (WebView) findViewById(R.id.webview);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.loadUrl("file:///android_asset/im_ssl2nd.jpg");
        mWebView.getSettings().setSupportZoom(true);
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        mWebView.setScrollbarFadingEnabled(true);
        
        ZoomControls zoomControls = (ZoomControls)findViewById(R.id.zoomControls1);
        zoomControls.setOnZoomInClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
            	mWebView.zoomIn();
            	mWebView.zoomIn();
            }
        });
        zoomControls.setOnZoomOutClickListener(new View.OnClickListener() {
             @Override
             public void onClick(View v) {
                 mWebView.zoomOut();
                 mWebView.zoomOut();
             }
        });
    
        
        username = ApplicationService.getUserName();        
        library = ApplicationService.getLibrary();
        user_level = ApplicationService.getLevel();
        user_seat = ApplicationService.getSeat();

        // Initialize buttons
		seat1_bn = (Button) findViewById(R.id.ssl2_seat_1);
		seat2_bn = (Button) findViewById(R.id.ssl2_seat_2);
		seat3_bn = (Button) findViewById(R.id.ssl2_seat_3);		
		seat4_bn = (Button) findViewById(R.id.ssl2_seat_4);
		seatStatus  = new ArrayList();	 
        
        // Get the message from the intent
        Intent intent = getIntent();

        // Chat mode
        if(intent.getStringExtra(ChatActivity.CHAT_EXTRA_MODE) != null) {
        	mode = 0;
        	ApplicationService.inform("Start chatting");
        } else if(intent.getStringExtra(SignInWithLocActivity.SIGNIN_WL_EXTRA_MODE) != null) 
        {
        	// Sign in mode
	        mode = 1;
	        username = ApplicationService.getUserName();
	        ApplicationService.inform("Select your seat");
        }
        
        getOnlineSeats();       
    }

    /* Called when the user clicks any seat */
    public void onClickHandler(View view) {
    	PaintDrawable drawable;
    	int color, button_index;
    	
    	// Chat mode	
    	if(mode == 0) 
    	{
	    	intent = new Intent(SSL2Activity.this, MessageBoardActivity.class);            	
	    	intent.putExtra(SELECTED_LEVEL, "2");	
    		
	    	switch(view.getId()) 
	    	{
	    		case R.id.ssl2_seat_1:  
	    			if(Integer.parseInt(seatStatus.get(0).toString()) == 1)
	    			{
	    				intent.putExtra(SELECTED_SEAT, "1");
	    				startActivity(intent);	    				
	    			} else {
	    				ApplicationService.inform("The message board is not available.");
	    			}
	    			 
	    			break;
	    		case R.id.ssl2_seat_2:
	    			if(Integer.parseInt(seatStatus.get(1).toString()) == 1)
	    			{
	    				intent.putExtra(SELECTED_SEAT, "2");
	    				startActivity(intent);	    				
	    			} else {
	    				ApplicationService.inform("The message board is not available.");
	    			}
	    			break;
	    		case R.id.ssl2_seat_3:
	    			if(Integer.parseInt(seatStatus.get(2).toString()) == 1)
	    			{
	    				intent.putExtra(SELECTED_SEAT, "3");
	    				startActivity(intent);	    				
	    			} else {
	    				ApplicationService.inform("The message board is not available.");
	    			}
	    			break;
	    		case R.id.ssl2_seat_4:
	    			if(Integer.parseInt(seatStatus.get(3).toString()) == 1)
	    			{
	    				intent.putExtra(SELECTED_SEAT, "4");
	    				startActivity(intent);	    				
	    			} else {
	    				ApplicationService.inform("The message board is not available.");
	    			}
	    			break;    			
	    	}  	    		    			    	    	      	
    	}
    	else 
    	{
    		// Sign in mode
	    	switch(view.getId()) 
	    	{
	    		case R.id.ssl2_seat_1:
	    			 if(Integer.parseInt(seatStatus.get(0).toString()) == 1)
	    			 {
	    				 ApplicationService.inform("Seat is already selected.");
	    			 } else {
	    				 alertSignInDialog(2, 1);
	    			 }
	    			 
	    			break;
	    		case R.id.ssl2_seat_2:
	    			 if(Integer.parseInt(seatStatus.get(1).toString()) == 1)
	    			 {
	    				 ApplicationService.inform("Seat is already selected.");	    				 
	    			 } else {
	    				 alertSignInDialog(2, 2);
	    			 }
	    			break;
	    		case R.id.ssl2_seat_3:
	    			 if(Integer.parseInt(seatStatus.get(2).toString()) == 1)
	    			 {
	    				 ApplicationService.inform("Seat is already selected.");	    				 
	    			 } else {
	    				 alertSignInDialog(2, 3);
	    			 }
	    			break;
	    		case R.id.ssl2_seat_4:
	    			 if(Integer.parseInt(seatStatus.get(3).toString()) == 1)
	    			 {
	    				 ApplicationService.inform("Seat is already selected.");
	    			 } else {
	    				 alertSignInDialog(2, 4);
	    			 }
	    			break;    			
	    	}
    	}  	
    }
    
    public void getOnlineSeats()
    {
    	String url = HOSTNAME + GET_ONLINE_USERS_URL + "?library=" + library + "&level=2";           
    	
    	// Get current messages
    	new GetJSONArrayTask(){
    		@Override
    		protected void onPostExecute(JSONArray result){
				if(result == null){
					ApplicationService.inform(getString(R.string.nointernet));
					finish();
					return;
				}         		

				// Reset to the default color
				seat1_bn.setBackgroundColor(Color.GRAY);
				seatStatus.add("0");
				seat2_bn.setBackgroundColor(Color.GRAY);
				seatStatus.add("0");
				seat3_bn.setBackgroundColor(Color.GRAY);
				seatStatus.add("0");
				seat4_bn.setBackgroundColor(Color.GRAY);
				seatStatus.add("0");
				
				// Parse JSON Object				
                try{
                	for(int i=0; i<result.length(); i++) {
                		
                		JSONObject json_data = result.getJSONObject(i);

                		switch(Integer.parseInt(json_data.getString("seat")))
                		{
                			case 1:
                				if((user_level == 2) && (user_seat == 1)) {
                					seat1_bn.setBackgroundColor(Color.RED);
                		    	}else {
                		    		seat1_bn.setBackgroundColor(Color.GREEN);
                		    	}
                		    	
                				seatStatus.set(0, "1");
                				break;
                			case 2:
                				if((user_level == 2) && (user_seat == 2)) {
                					seat2_bn.setBackgroundColor(Color.RED);
                		    	}else {
                		    		seat2_bn.setBackgroundColor(Color.GREEN);
                		    	}
                				
                				seatStatus.set(1, "1");
                				break;
                			case 3:
                				if((user_level == 2) && (user_seat == 3)) {
                					seat3_bn.setBackgroundColor(Color.RED);
                		    	}else {
                		    		seat3_bn.setBackgroundColor(Color.GREEN);
                		    	}
                				
                				seatStatus.set(2, "1");
                				break;
                			case 4:
                				if((user_level == 2) && (user_seat == 4)) {
                					seat4_bn.setBackgroundColor(Color.RED);
                		    	}else {
                		    		seat4_bn.setBackgroundColor(Color.GREEN);
                		    	}
                				
                				seatStatus.set(3, "1");
                				break;                				
                		}

                	}                	                	
                }
                catch(JSONException e){
                	Log.e(TAG, "Error parsing data "+e.toString());
                }         		
         	}	
        }.execute(url.replaceAll(" ", "%20"));	    	
    }    
    
	public void alertSignInDialog (int level, int seat) 
	{
		final int selected_level = level;
		final int selected_seat = seat;
		
		AlertDialog.Builder alertDialog = new AlertDialog.Builder(SSL2Activity.this);
		alertDialog.setTitle("Locate yourself");
		alertDialog.setMessage("Is your location at " + library + " on level " + selected_level + " on seat " + selected_seat + " ?");
		
		alertDialog.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
			public void onClick(DialogInterface arg0, int arg1) {
				ApplicationService.setLevel(2);
				ApplicationService.setSeat(selected_seat);
		        user_level = 2;
		        user_seat = selected_seat;
		        
		        updateUserSeat();
		    				
			}});
		
		alertDialog.setNegativeButton("Cancel", null);		
		
		alertDialog.show();
	}
	
	
    private void updateUserSeat(){
    	
    	intent = new Intent(SSL2Activity.this, ChatActivity.class); 
    	String url = HOSTNAME + AUTHENTICATION_URL + "?devicetoken=" + ApplicationService.getDeviceID() + "&library=" + library + "&level=" + user_level + "&seat=" + user_seat + "&name=" + username + "&interest=" + ApplicationService.getAreaOfInterest();    	
    	
    	// Register the user with default name    	
    	new GetJSONObjectTask(){
    		@Override
    		protected void onPostExecute(JSONObject result){
				if(result == null){
					ApplicationService.inform(getString(R.string.nointernet));
					finish();
					return;
				}         		
				
				// Parse JSON Object				
                try{
                	String authen = result.getString("result");
                	
                	if((authen.length() != 0) && authen.equals("Success"))
                	{
                		startActivity(intent);
                	}else {
                		ApplicationService.inform("Connection errored");
    					finish();
    					return;                		
                	}
                	
                	
                }
                catch(JSONException e){
                	Log.e(TAG, "Error parsing data "+e.toString());
                }         		
         	}	
        }.execute(url.replaceAll(" ", "%20"));	
    }	
	 @Override
	    public void onBackPressed()
	    {
			AlertDialog.Builder alertDialog = new AlertDialog.Builder(SSL2Activity.this);
			alertDialog.setTitle("Exit this application");
			alertDialog.setMessage("Are you sure you want to close this application?");
			
			alertDialog.setPositiveButton("Confirm", new DialogInterface.OnClickListener() {
				public void onClick(DialogInterface arg0, int arg1) {
					
					finish();
					SignInWithLocActivity.signInWithLocActivity.finish();
					SignInWithNameActivity.signInWithNameActivity.finish();
					SignInActivity.signinActivity.finish();
					LibListActivity.libListActivity.finish();
				}});
			
			alertDialog.setNegativeButton("Cancel", null);		
			
			if(mode==0)
			{
				alertDialog.show();
			}
			else
			{
				super.onBackPressed();
			}
	    }
}
